package cn.craftyun.yunexam.controller;

import cn.craftyun.yunexam.entity.User;
import cn.craftyun.yunexam.request.UserLoginRequest;
import cn.craftyun.yunexam.service.UserService;
import cn.craftyun.yunexam.vo.ResultEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户登录
     *
     * @param userLoginRequest 请求对象
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResultEntity login(@RequestBody @Valid UserLoginRequest userLoginRequest, HttpServletRequest request) {
        User user = userService.findByStuNumber(userLoginRequest.getStuNumber());
        if (user == null) {
            return ResultEntity.error("用户不存在", null);
        }
        if (!userLoginRequest.getPassword().equals(user.getPassword())) {
            return ResultEntity.error("用户密码错误", null);
        }
        // 抹去用户的密码
        user.setPassword(null);
        // 设置session
        request.getSession().setAttribute("examUser", user);
        // 返回登录成功的结果
        return ResultEntity.success("登录成功", user);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public ResultEntity getInfo() {
        User user = userService.getLoginUser();
        return ResultEntity.success("获取信息成功", user);
    }
}
